from django import template
from django.contrib.messages.constants import (
    DEFAULT_TAGS, DEBUG, INFO, SUCCESS, WARNING, ERROR
)
from django.template.defaultfilters import stringfilter

from user.models import User
from exam.models import ExamPaper

register = template.Library()


@register.filter
@stringfilter
def message_2_bootstrap_alert(obj):
    if obj == DEFAULT_TAGS[DEBUG]:
        return 'alert-info'
    elif obj == DEFAULT_TAGS[INFO]:
        return 'alert-info'
    elif obj == DEFAULT_TAGS[SUCCESS]:
        return 'alert-success'
    elif obj == DEFAULT_TAGS[WARNING]:
        return 'alert-warning'
    elif obj == DEFAULT_TAGS[ERROR]:
        return 'alert-danger'
    else:
        print('[ERROR]Unknown message tag: ' + obj + ', pls check')
        return 'ERROR'


@register.filter
def model_name(obj):
    try:
        return obj._meta.model_name
    except AttributeError:
        return None


@register.filter
def get_answer(problem, user_id):
    user = User.objects.get(pk=user_id)
    exam_paper, created = ExamPaper.objects.get_or_create(
        exam=problem.exam, student=user)
    return problem.answers.filter(exam_paper=exam_paper.id)[0]


@register.filter
def get_exam_paper(exam, user_id):
    user = User.objects.get(pk=user_id)
    return exam.exam_papers.get(student=user)


@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)


@register.filter
def get_student_semester_class(student, slug):
    return student.enrolling.filter(slug=slug).order_by('-id')


@register.filter
def get_exampaper(exam, student):
    return ExamPaper.objects.filter(exam=exam, student=student).first()


@register.simple_tag
def url_replace(request, field, value):
    dict_ = request.GET.copy()
    dict_[field] = value
    return dict_.urlencode()
